package com.ruoyi.web.controller.system;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.jwt.JWTUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.UserInfo;
import com.ruoyi.system.service.IUserInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

@RestController
@RequestMapping("/system/info")
public class UserInfoController extends BaseController {
    @Autowired
    private IUserInfoService userInfoService;

    /**
     * 调用 wx.login() 获取临时登录凭证code 并回传到开发者服务器。
     * 调用 auth.code2Session 接口，换取用户唯一标识 OpenID、 用户在微信开放平台账号下的唯一标识 UnionID（若当前小程序已绑定到微信开放平台账号）、会话密钥 session_key。
     * 根据 openid 创建 token 让前端存储到缓存中
     */
    @RequestMapping("/login")
    public AjaxResult login(String code) throws IOException {
        System.out.println(code);
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx4c7d9b74a219944d&secret=dd8079dab29e1061a2a82e65bcafd33e&grant_type=authorization_code&js_code=" + code;
        // 1. 根据前端传来的临时凭证去获取 openid
        HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET");
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = null;
        StringBuffer sb = new StringBuffer();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        System.out.println("Https Response: " + sb.toString());

        // 2. 创建正则表达式截取 openid
        Pattern pattern = Pattern.compile("\"openid\":\"([^\"]+)\"");
        Matcher matcher = pattern.matcher(sb);

        if (matcher.find()) {
            String openid = matcher.group(1);
            System.out.println("Extracted openid: " + openid);      // 输出: o_4L166BegF2bNj7-gpTgWjGYkwM

            // 3. 根据 openid 去数据库搜索该用户是否已经存在
            TableDataInfo list = list(new UserInfo(openid));
            logger.info("list:{}", list.getTotal());
            if (list.getTotal() == 0) {         // 如果数据库中不存在该 openid 就存进去 说明是第一次登录
                add(new UserInfo(openid));      // 可以只传 openid 除了用户头像其他都有默认值
                list = list(new UserInfo(openid));
            }
            // 4. 拿到用户的 id 将 id 和 openid 制作 token 并返回前端
            UserInfo user = (UserInfo) list.getRows().get(0);
            return AjaxResult.success("操作成功", JWTUtil.getToken(user.getId(), openid));
        } else {
            return AjaxResult.error("No openid match found");
        }
    }

    @PostMapping
    public AjaxResult add(@RequestBody UserInfo userInfo) {
        return toAjax(userInfoService.insertUserInfo(userInfo));
    }

    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(userInfoService.deleteUserInfoByIds(ids));
    }

    @PutMapping
    public AjaxResult edit(@RequestBody UserInfo userInfo) {
        return toAjax(userInfoService.updateUserInfo(userInfo));
    }

    // 只能根据 id 查
    @GetMapping(value = "/{id}")
    @Anonymous
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(userInfoService.selectUserInfoById(id));
    }

    // 传入用户实体类查询
    @GetMapping("/list")
    public TableDataInfo list(UserInfo userInfo) {
        startPage();
        List<UserInfo> list = userInfoService.selectUserInfoList(userInfo);
        return getDataTable(list);
    }

}
